package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * @param dishDTO
     */
    @Transactional //开始声明式事务
    @Override
    public void save(DishDTO dishDTO) {
        //1.保存菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //这里设置了主键返回
        dishMapper.save(dish);
        //2.保存口味信息
        //注意:这里需要给每个口味对象设置dishId
        List<DishFlavor> flavorList = dishDTO.getFlavors().stream()
                .map(dishFlavor -> {
                    dishFlavor.setDishId(dish.getId());
                    return dishFlavor;
                })
                .collect(Collectors.toList());
        dishFlavorMapper.saveDishFlavor(flavorList);

        //清理缓存
        String CACHE_KEY = "DISH_"+dishDTO.getCategoryId();
        redisTemplate.delete(CACHE_KEY);

    }

    /**
     * 菜品分页查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        //Dish不好使和页面对不上,少了个分类名称
        Page<Dish> page =dishMapper.page(pageQueryDTO);
        //根据每个菜品的分类id去查询分类的名称
        //包装成vo对象返回
        List<DishVO> list = page.getResult().stream()
                .map(dish -> {
                    DishVO dishVO = new DishVO();
                    BeanUtils.copyProperties(dish, dishVO);
                    //根据 category_id 查询分类信息
                    Category category = categoryMapper.findById(dish.getCategoryId());
                    dishVO.setCategoryName(category.getName());
                    return dishVO;
                })
                .collect(Collectors.toList());

        return new PageResult(page.getTotal(),list);

    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void delByIds(List<Long> ids) {
        //todo 待完成
        //1.菜品起售不能删除(对每条数据单独查询)
        //ids.forEach(id->{
            //根据id查询菜品
            //如果菜品的状态是 1
            //return;
        //});
        //2.套餐关联了菜品不能删(foreach一条sql查询)
        //根据ids查询是否有套餐关联了
        //select setmeal_id from setmeal_dish where dish_id in (ids的集合)

        dishMapper.delByIds(ids);
        dishFlavorMapper.delByDishIds(ids);

        //清理缓存
        //现在这里拿到的ids是菜品的id 构造的CACHE_KEY 是根据分类id来构造的
        //这里直接把所有DISH_分类id的数据全删除
        //获取所有key
        Set keys = redisTemplate.keys("DISH_*");
        redisTemplate.delete(keys);
    }

    /**
     * 条件查询菜品和口味
     * @return
     */
    public List<DishVO> listWithFlavor(DishDTO dishDTO) {
        String CACHE_KEY = "DISH_"+dishDTO.getCategoryId();
        //1.查缓存
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(CACHE_KEY);
        //2.判断
        if(dishVOList != null){
            return dishVOList;
        }

        List<Dish> dishList = dishMapper.findDishesByCid(dishDTO);
        dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.findByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //3.存缓存
        redisTemplate.opsForValue().set(CACHE_KEY,dishVOList);
        return dishVOList;
    }
}
